<template>
  <div class="app-attract">
    <!-- 筛选 -->
    <Screen
      :RadioList="radioList"
      :pickerList="pickerList"
      :inputList="inputList"
      @dateChange="dateChange"
      @search="search"
      @statusChange="
        ScreenGroupChange($event, listQuery, radioList, 'activity_status')
      "
      @unionChange="ScreenGroupChange($event, listQuery, radioList, 'union_id')"
      @tagClose="tagClose"
    >
      <template #mainbtn>
        <el-button
          type="primary"
          @click="openGroup"
          v-if="
            $store.getters.roles_name == 'attract' && $store.getters.leader == 1
          "
          >开团</el-button
        >
      </template>
    </Screen>

    <!-- 表格 -->
    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"
      fit
      highlight-current-row
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <el-table-column label="团信息" width="260">
        <template slot-scope="scope">
          <div class="act_message text-last">
            <div
              @click="
                scope.row.activity_type == 1 ? backToDetail(scope.row) : ''
              "
              class="link-type"
            >
              {{ scope.row.title }}
            </div>
            <div>团ID:{{ scope.row.activity_id }}</div>
            <span class="orred" v-if="scope.row.union_id == 2011251395">{{
              checkAttract(scope.row.union_id)
            }}</span>
            <span class="orwarning" v-if="scope.row.union_id == 2011732746">{{
              checkAttract(scope.row.union_id)
            }}</span>
            <span v-if="scope.row.union_id == 0" class="orgray">线下</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="团状态"
        width="180px"
        align="center"
        prop="status"
      >
        <template slot-scope="scope">
          <el-link :underline="false" v-if="scope.row.activity_status == 0"
            >未发布</el-link
          >
          <el-link
            type="primary"
            :underline="false"
            v-if="scope.row.activity_status == 1"
            >报名中</el-link
          >
          <el-link
            type="success"
            :underline="false"
            v-if="scope.row.activity_status == 2"
            >进行中</el-link
          >
          <el-link
            type="danger"
            :underline="false"
            v-if="scope.row.activity_status == 3"
            >已删除</el-link
          >
          <el-link
            type="warning"
            :underline="false"
            v-if="scope.row.activity_status == 4"
            >已终止</el-link
          >
          <el-link
            type="info"
            :underline="false"
            v-if="scope.row.activity_status == 5"
            >已结束</el-link
          >
        </template>
      </el-table-column>
      <el-table-column label="活动时间" align="center">
        <template slot-scope="scope">
          <div>起：{{ scope.row.start_time }}</div>
          <div>止：{{ scope.row.end_time }}</div>
        </template>
      </el-table-column>
      <el-table-column label="提报商品">
        <template slot-scope="scope">
          <div class="act_message text-last">
            <div>报名商品：{{ scope.row.sku_total_cnt }}</div>
            <div>待审核品：{{ scope.row.sku_to_examine_cnt }}</div>
            <div>
              审核通过：{{ scope.row.sku_cnt }}
              <span
                v-if="
                  (($store.getters.roles_name == 'attract' &&
                    $store.getters.leader == 1) ||
                    $store.getters.roles_name == 'admin' ||
                    $store.getters.roles_name == 'general') &&
                  scope.row.fail_count > 0 &&
                  scope.row.user_list
                "
                style="color: red"
                >{{ scope.row.fail_count }}</span
              >
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="活动效果">
        <template slot-scope="scope">
          <div class="act_message text-last">
            <div>订单引入量：{{ scope.row.order_cnt_in }}</div>
            <div>预估服务费：{{ scope.row.yg_service_fee }}</div>
            <div>实际服务费：{{ scope.row.service_fee }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="招商" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.user_list">
            <span
              v-for="(item, index) in scope.row.user_list"
              :key="index"
              style="text-align: left"
            >
              {{ item.manage_name }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="组长" align="center">
        <template slot-scope="scope">
          <span>{{ getDockingName(scope.row.op_id) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <div class="handle">
            <el-button
              type="text"
              size="mini"
              @click="exportGoods(scope.row.activity_id)"
              >导出商品</el-button
            >
            <el-button
              type="text"
              size="mini"
              @click="
                handleClipboard(
                  `https://jzt.jd.com/jtk/#/orient-act-info?id=${scope.row.activity_id}_7`,
                  $event
                )
              "
              >复制链接</el-button
            >
            <el-button type="text" size="mini" @click="lookEffect(scope.row)"
              >查看效果</el-button
            >
            <el-button
              type="text"
              size="mini"
              @click="addDocking(scope.row)"
              v-if="
                ($store.getters.roles_name == 'attract' &&
                  $store.getters.leader == 1) ||
                $store.getters.roles_name == 'admin' ||
                $store.getters.roles_name == 'general'
              "
              >添加招商</el-button
            >
          </div>
        </template>
      </el-table-column>
      <template slot="empty">
        <div>
          <img src="~@/assets/images/nodata.png" alt class="nodata" />
          <div style="font-size: 14px">暂无数据</div>
        </div>
      </template>
    </el-table>

    <drawer ref="groupmessage" />

    <el-dialog
      title="提示"
      :visible.sync="dockingDialogVisible"
      width="30%"
      :before-close="handleClose"
      top="30vh"
    >
      <div>{{ thisTeaminfo.title }}</div>
      <div>活动ID：{{ thisTeaminfo.activity_id }}</div>
      <div>
        活动时间:{{ thisTeaminfo.start_time }}-{{ thisTeaminfo.end_time }}
      </div>
      <div class="notice">
        注意:招商添加后不可删除，只能新增招商，请谨慎选择招商！
      </div>
      <el-button type="primary" @click="allcheck">全选</el-button>
      <div v-loading="loading">
        <div style="margin: 15px 0"></div>
        <el-checkbox-group v-model="userList">
          <el-checkbox
            v-for="(item, index) in dockingList"
            :key="index"
            :label="item.username"
            :disabled="isDisable(item.username)"
          ></el-checkbox>
        </el-checkbox-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dockingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <Pagination
      :page="listQuery.page"
      :psize="listQuery.psize"
      :total="total"
      @SizeChange="handleSizeChange"
      @CurrentChange="handleCurrentChange"
    />
  </div>
</template>

<script>
import drawer from "./group/openGroup";
import Screen from "@/components/Screen";
import {
  getGroupList,
  getDockingList,
  postDockingList,
  getOpenGroupList,
  exportActivityGoods,
} from "@/api/attract";
import { getDockingName } from "@/utils/helper";
import { format } from "@/utils/formatDate";
import clipboard from "@/utils/clipboard";
import tableHeaderFixed from "@/mixins/tableHeaderFixed";
import screen from "@/mixins/screen";
import { ref, reactive } from "vue";
export default {
  name: "group",
  mixins: [tableHeaderFixed, screen],
  components: {
    drawer,
    Screen,
  },

  data() {
    return {
      const state=reactive({
        list:[],
        tatal:0,
        listQuery: {
        page: 1,
        psize: 20,
        activity_from: 1,
        created_at: `${format(Date.now() - 3600 * 1000 * 24 * 30)} ~ ${format(
          Date.now()
        )}`,
        let message=ref("")
        union_id: -1,
        activity_status: -1,
        activity_search: "",
        },
      })


      openlist: [],
      list: [],
      total: 0,
      listLoading: false,
      dockingDialogVisible: false,
      thisTeaminfo: {},
      dockingList: [],
      userList: [],
      disabledUserList: [],
      loading: false,
      listQuery: {
        page: 1,
        psize: 20,
        activity_from: 1,
        created_at: `${format(Date.now() - 3600 * 1000 * 24 * 30)} ~ ${format(
          Date.now()
        )}`,
        union_id: -1,
        activity_status: -1,
        activity_search: "",
      },
      message: "",
      startDate: [`${format(Date.now())}`, `${format(Date.now())}`],
      radioList: [
        {
          label: "联盟",
          list: [{ name: "全部", id: -1 }],
          data: "全部",
          event: "union",
          field: "union_id",
        },
        {
          label: "状态",
          list: [
            { name: "全部", id: -1 },
            { name: "未发布", id: 0 },
            { name: "报名中", id: 1 },
            { name: "进行中", id: 2 },
            { name: "已删除", id: 3 },
            { name: "已终止", id: 4 },
            { name: "已结束", id: 5 },
          ],
          data: "全部",
          event: "status",
          field: "activity_status", //判断叉掉的筛选字段
        },
      ],
      inputList: [
        {
          label: "团信息",
          data: "",
          place: "活动ID/团名称",
        },
        {
          isbtn: true,
          btnlabel: "搜索",
          type: "primary",
          plain: false,
        },
        {
          isbtn: true,
          btnlabel: "重置",
          type: "info",
          plain: true,
        },
      ],
      pickerList: [
        {
          label: "下单时间",
          date: [
            `${format(Date.now() - 3600 * 1000 * 24 * 30)}`,
            `${format(Date.now())}`,
          ],
          pickerOptions: {
            shortcuts: [
              {
                text: "今日",
                onClick(picker) {
                  let date = new Date();
                  const end = new Date();
                  const start = new Date();
                  picker.$emit("pick", [start, end]);
                },
              },
              {
                text: "昨日",
                onClick(picker) {
                  let date = new Date();
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24);
                  end.setTime(end.getTime() - 3600 * 1000 * 24);
                  picker.$emit("pick", [start, end]);
                },
              },
              {
                text: "最近七天",
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit("pick", [start, end]);
                },
              },
              {
                text: "最近14天",
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 14);
                  picker.$emit("pick", [start, end]);
                },
              },
              {
                text: "最近一个月",
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                  picker.$emit("pick", [start, end]);
                },
              },
            ],
          },
        },
      ],
    };
  },
  created() {
    this.$store.getters.unionlist.forEach((element) => {
      this.radioList[0].list.push(element);
    });
    this.radioList[0].list.push({
      id: 0,
      name: "线下",
    });
    this.fetchList();
    this.getOpenGroup();
  },
  methods: {
    getDockingName,
    fetchList(obj = {}) {
      this.listLoading = true;
      if (Object.keys(obj).length == 0) {
        getGroupList(this.listQuery).then((res) => {
          this.list = res.data.data;
          this.total = res.data.total;
          this.listLoading = false;
        });
      } else {
        getGroupList(obj).then((res) => {
          this.list = res.data.data;
          this.total = res.data.total;
          this.listLoading = false;
        });
      }
    },
    allcheck() {
      this.userList = this.dockingList.map((v) => v.username);
    },
    handleSizeChange(val) {
      this.listQuery.psize = val;
      this.fetchList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.fetchList();
    },
    isDisable(name) {
      return this.disabledUserList.find((item) => item == name) ? true : false;
    },
    search() {
      this.listQuery.activity_search = this.inputList[0].data;
      this.fetchList();
    },
    handleClose(done) {
      done();
    },

    reset() {
      // for (const key in this.sizeForm) {
      //   this.$set(this.sizeForm, key, "全部");
      // }
      // this.startDate = [];
      // this.$set(this.startDate, 0, 1, "");
      // this.message = "";
    },
    openGroup() {
      this.$refs.groupmessage.dialogFormVisible = true;
    },
    checkAttract(id) {
      return this.$store.getters.unionlist.find((item) => {
        return item.id == id;
      })?.name;
    },
    addDocking(val) {
      this.thisTeaminfo = val;
      this.loading = true;
      getDockingList({ op_id: val.op_id }).then((res) => {
        this.dockingList = res.data;
        val.user_list?.forEach((v) => {
          this.userList.push(v.manage_name);
          this.disabledUserList.push(v.manage_name);
        });
        this.loading = false;
      });
      this.dockingDialogVisible = true;
    },
    sureAdd() {
      let postList = [];
      this.userList.forEach((item) => {
        const obj = {};
        obj[
          this.$store.getters.adminlist.find((v) => {
            return v.name == item;
          })?.id
        ] = item;
        postList.push(obj);
      });
      postDockingList({
        id: this.thisTeaminfo.id,
        userList: JSON.stringify(postList),
      }).then((res) => {
        if (res.code == 10000) {
          this.$message({
            type: "success",
            message: "添加成功!",
          });
        } else {
          this.$message({
            type: "error",
            message: "添加失败!",
          });
        }
      });
      this.dockingDialogVisible = false;
      this.fetchList();
    },
    // 复制
    handleClipboard(text, event) {
      clipboard(text, event);
    },
    lookEffect(val) {
      let ids = {};
      ids.id = val.id;
      ids.activity_id = val.activity_id;
      ids.source = "ActivityEffect";
      this.$router.push({
        path: "/attract/activity_detail",
        query: ids,
      });
    },
    exportGoods(activity_id) {
      exportActivityGoods(activity_id).then((res) => {
        if (res.status == "1") {
          let url = res.data;
          window.open(url, "_blank");
        }
      });
    },
    backToDetail(val) {
      let ids = {};
      ids.id = val.id;
      ids.activity_id = val.activity_id;
      this.$router.push({
        path: "/attract/activity_detail",
        query: ids,
      });
    },
    dateChange(date) {
      // console.log(date);
      this.listQuery.created_at = `${date[0]} ~ ${date[1]}`;
      this.fetchList();
    },
    //联盟
    getOpenGroup() {
      getOpenGroupList().then((res) => {
        this.openlist = res.data;
        let a = "";
        this.openlist.forEach((v) => {
          a += `<strong>${v}</strong>`;
        });
        this.$notify({
          dangerouslyUseHTMLString: true,
          message: a,
          showClose: false,
        });
      });
    },
  },
  watch: {
    dockingDialogVisible(newval, oldval) {
      if (newval == false) {
        this.disabledUserList = [];
        this.userList = [];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
